package com.canbot.u05.activity.agenda

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.agenda.adapter.AgendaDanceAdapter
import com.canbot.u05.activity.agenda.bean.AgendaDanceBean
import com.canbot.u05.activity.agenda.bean.AgendaTypeBean
import com.canbot.u05.activity.agenda.dialog.TipMsgDialog
import com.canbot.u05.activity.agenda.interfaces.IAgendaDanceLisenter
import com.canbot.u05.activity.loge
import com.canbot.u05.activity.presidemode.newcode.BaseHostActivity
import com.canbot.u05.activity.presidemode.newcode.bean.NetLoadUtil
import com.canbot.u05.activity.presidemode.newcode.interfaces.IResponse
import com.canbot.u05.activity.reception.ReceptionModeSettingActivity
import com.canbot.u05.activity.shoppingGuide.codeMarketing.CodeMarketingActivity
import com.canbot.u05.activity.shoppingGuide.sales.SellModePropagandaActivity
import com.canbot.u05.activity.vipguide.VipGuideActivity
import com.canbot.u05.bean.UsherDataInfo
import com.canbot.u05.bean.VipPersonMapData
import com.canbot.u05.bean.codeMarketing.CodeMarketingInfo
import com.canbot.u05.bean.sales.SellInfo
import com.canbot.u05.utils.PathConst
import com.canbot.u05.utils.ToastTools
import kotlinx.android.synthetic.main.activity_agenda_type_dance.*
import java.util.*
import kotlin.collections.ArrayList

/**
 * @author yinxiaowei
 * @date 2019/5/31
 */
class AgendaDataListActivity : BaseHostActivity(), IResponse<String> {
    private val voices = arrayOf(arrayOf("${PathConst.AGENDA_VOICE_DIR}jtrw_gzrc_u05_001.mp3", "32"),
            arrayOf("${PathConst.AGENDA_VOICE_DIR}jtrw_gzrc_u05_002.mp3", "24"))

    override fun onSucusse(result: String?) {
        dismissDialog()
        if (result == null) {
            showEmptyView()
        } else {
            result.apply {
                loge("onSucusse==  $result")
                when (requestCode) {
                    REQUEST_VIDEO, REQUEST_MUSIC -> {
                        val agendaDanceBean = JSON.parseArray(result, AgendaDanceBean::class.java)
                        if (agendaDanceBean.size == 0) {
                            showEmptyView()
                        } else {
                            agendaTypeBeanList.addAll(agendaDanceBean)
                            updateSelect()
                            runOnUiThread { adapter.notifyDataSetChanged() }
                        }
                    }

                    REQUEST_HBXC -> {
                        val codeMarketingInfo: CodeMarketingInfo? = JSON.parseObject(result, CodeMarketingInfo::class.java)
                        if (codeMarketingInfo != null ) {
                            val element = AgendaDanceBean(getString(R.string.module_name_hbxc))
                            /*agendaTypeBeanList.add(element)
                            updateSelect()
                            runOnUiThread { adapter.notifyDataSetChanged() }*/
                            agendaSelectList.add(element)
                            exit()
                        } else {
                            showEmptyView()
                        }
                    }
                    REQUEST_YBJD -> {
                        val usherDataInfo: UsherDataInfo? = JSON.parseObject(result, UsherDataInfo::class.java)
                        if (usherDataInfo != null && !usherDataInfo.isEmpty) {
                            val element = AgendaDanceBean(usherDataInfo.voiceContent)
                            /*agendaTypeBeanList.add(element)
                            updateSelect()
                            runOnUiThread { adapter.notifyDataSetChanged() }*/
                            agendaSelectList.add(element)
                            exit()
                        } else {
                            showEmptyView()
                        }
                    }
                    REQUEST_GBYD -> {
                        val list = JSON.parseArray(result, VipPersonMapData::class.java)
                        if (list.size > 0) {
                            val element = AgendaDanceBean(list[0].name)
                            agendaSelectList.add(element)
                            exit()
                        } else {
                            showEmptyView()
                        }
                    }
                }
            }
        }
    }

    /**
     * 显示空信息
     */
    private fun showEmptyView() {
        runOnUiThread {
            when (requestCode) {
                REQUEST_VIDEO -> {
                    layout_empty_audio.visibility = View.VISIBLE
                    agenda_data_empty_tv.text = getString(R.string.video_null_tips)
                }

                REQUEST_MUSIC -> {
                    layout_empty_audio.visibility = View.VISIBLE
                    agenda_data_empty_tv.text = getString(R.string.audio_null_tips)
                }
                else -> {
                    layout_empty.visibility = View.VISIBLE
                }
            }
        }
    }

    /**
     * 隐藏空信息
     */
    private fun hideEmptyView() {
        runOnUiThread {
            layout_empty.visibility = View.GONE
            layout_empty_audio.visibility = View.GONE
        }
    }

    override fun onFailuer(result: String?) {
        dismissDialog()
        ToastTools.newInstance(this).showText(result)
    }

    fun gotoSettings(view: View) {
        if (requestCode != -1) {
            var intent: Intent? = null
            when (requestCode) {
                REQUEST_CXLK -> {
                    intent = Intent(this, SellModePropagandaActivity::class.java)
                }
                REQUEST_GBYD -> {
                    intent = Intent(this, VipGuideActivity::class.java)
                }
                REQUEST_YBJD -> {
                    intent = Intent(this, ReceptionModeSettingActivity::class.java)
                }
                REQUEST_HBXC -> {
                    intent = Intent(this, CodeMarketingActivity::class.java)
                }
            }
            intent?.let {
                gotoActivity(it)
            }
        }
    }

    private val agendaTypeBeanList = ArrayList<AgendaDanceBean>()
    private var agendaSelectList = ArrayList<AgendaDanceBean>()
    private lateinit var adapter: AgendaDanceAdapter
    private lateinit var itemTouchHelper: ItemTouchHelper
    private lateinit var context: Context
    override fun initEventData() {
        context = this
        getIntentData()
        recycleView_data_list.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        adapter = AgendaDanceAdapter(agendaTypeBeanList, this, object : IAgendaDanceLisenter {
            override fun onSelect(agendaDanceBean: AgendaDanceBean) {
                agendaTypeBeanList.find {
                    it == agendaDanceBean
                }?.apply {
                    this.isSelect = !this.isSelect
                    adapter.notifyDataSetChanged()
                    if (this.isSelect) {
                        if (!agendaSelectList.contains(agendaDanceBean)) {
                            agendaSelectList.add(agendaDanceBean)
                        }
                    } else {
                        if (agendaSelectList.contains(agendaDanceBean)) {
                            agendaSelectList.remove(agendaDanceBean)
                        }
                    }
                }
            }
        })
        itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.Callback() {
            override fun getMovementFlags(p0: RecyclerView, p1: RecyclerView.ViewHolder): Int {
                val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
                val swipeFlags = 0
                return ItemTouchHelper.Callback.makeMovementFlags(dragFlags, swipeFlags)
            }

            override fun onMove(p0: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
                val fromPos = viewHolder.adapterPosition
                val toPos = target.adapterPosition
                Collections.swap(agendaTypeBeanList, fromPos, toPos)
                adapter.notifyItemMoved(fromPos, toPos)
                return true
            }

            override fun onSwiped(p0: RecyclerView.ViewHolder, p1: Int) {
            }

        })
        itemTouchHelper.attachToRecyclerView(recycleView_data_list)
        recycleView_data_list.adapter = adapter
        playRandomVoiceWithEmotion(voices)
    }

    private var agendaTypeBean: AgendaTypeBean? = null
    private fun getIntentData() {
        agendaTypeBean = intent.getSerializableExtra(DATA) as AgendaTypeBean?
        if (isTypeEqual()) {
            agendaTypeBean?.data?.apply {
                agendaSelectList.addAll(this)
            }
        }
    }

    private fun getDanceData() {
        val stringArray = resources.getStringArray(R.array.danceName)
        for (s in stringArray) {
            agendaTypeBeanList.add(AgendaDanceBean(s))
        }
        updateSelect()
    }

    override fun onResume() {
        super.onResume()
        if (isDebug) {
            getDanceData()
        } else {
            getData()
        }
    }

    private fun updateSelect() {
        hideEmptyView()
        if (isTypeEqual()) {
            for (agendaDanceBean in agendaTypeBeanList) {
                agendaTypeBean?.data?.find {
                    it == agendaDanceBean
                }?.apply {
                    agendaDanceBean.isSelect = this.isSelect
                }
            }
        }
    }

    private fun isTypeEqual(): Boolean {
        requestCode = intent.getIntExtra(KEY_REQUESTCODE, -1)
        if (requestCode != -1) {
            when (requestCode) {
                REQUEST_DANCE -> {
                    return agendaTypeBean?.type == getString(R.string.module_name_wdby)
                }
                REQUEST_VIDEO -> {
                    return agendaTypeBean?.type == getString(R.string.module_name_spbf)
                }
                REQUEST_MUSIC -> {
                    return agendaTypeBean?.type == getString(R.string.module_name_ypbf)
                }
                REQUEST_CXLK -> {
                    return agendaTypeBean?.type == getString(R.string.module_name_cxlk)
                }
                REQUEST_HBXC -> {
                    return agendaTypeBean?.type == getString(R.string.module_name_hbxc)
                }
                REQUEST_GBYD -> {
                    return agendaTypeBean?.type == getString(R.string.module_name_gbyd)
                }
                REQUEST_YBJD -> {
                    return agendaTypeBean?.type == getString(R.string.module_name_ybjd)
                }
            }
        }
        return false
    }

    private var requestCode: Int = -1
    private fun getData() {
        requestCode = intent.getIntExtra(KEY_REQUESTCODE, -1)
        if (requestCode != -1) {
            when (requestCode) {
                REQUEST_DANCE -> {
                    agenda_data_title.text = getString(R.string.module_name_wdby)
                    getDanceData()
                }
                REQUEST_VIDEO -> {
                    agenda_data_title.text = getString(R.string.module_name_spbf)
                    showLoadingDialog(getString(R.string.load_hint))
                    NetLoadUtil.loadVideoInfo(this, this)
                }
                REQUEST_MUSIC -> {
                    agenda_data_title.text = getString(R.string.module_name_ypbf)
                    showLoadingDialog(getString(R.string.load_hint))
                    NetLoadUtil.loadMusicInfo(this, this)
                }
                REQUEST_CXLK -> {
                    agenda_data_title.text = getString(R.string.module_name_cxlk)
                    showLoadingDialog(getString(R.string.load_hint))
                    NetLoadUtil.loadZXLKTaskList(this, object : IResponse<List<SellInfo>> {
                        override fun onSucusse(result: List<SellInfo>?) {
                            dismissDialog()
                            result?.let {
                                if (it.isNotEmpty()) {
                                    it.forEach { sellInfo ->
                                        agendaTypeBeanList.add(AgendaDanceBean(sellInfo.title))
                                    }
                                    updateSelect()
                                    runOnUiThread { adapter.notifyDataSetChanged() }
                                } else {
                                    showEmptyView()
                                }
                            }
                        }

                        override fun onFailuer(result: String?) {
                            dismissDialog()
                            ToastTools.newInstance(context).showText(result)
                        }
                    })
                }
                REQUEST_GBYD -> {
                    agenda_data_title.text = getString(R.string.module_name_gbyd)
                    showLoadingDialog(getString(R.string.load_hint))
                    NetLoadUtil.loadGBDYTaskList(this, this)
                }
                REQUEST_YBJD -> {
                    agenda_data_title.text = getString(R.string.module_name_ybjd)
                    showLoadingDialog(getString(R.string.load_hint))
                    NetLoadUtil.loadReceptionTaskList(this, this)
                }
                REQUEST_HBXC -> {
                    agenda_data_title.text = getString(R.string.module_name_hbxc)
                    showLoadingDialog(getString(R.string.load_hint))
                    NetLoadUtil.loadCodeMarkerTaskList(this, this)
                }
            }
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_agenda_type_dance
    }

    fun back(view: View) {
        exit()
    }

    private val TAG = AgendaDataListActivity::class.java.simpleName
    private fun exit() {
        Log.d(TAG, "exit data = ${agendaSelectList.size}")
        if (requestCode == REQUEST_DANCE && agendaSelectList.size > 0) {
            val tipMsgDialog = TipMsgDialog(this, getString(R.string.dance_tip))
            tipMsgDialog.setiDialogBtnLisenter {
                val intent = Intent()
                intent.putExtra(BaseHostActivity.DATA, agendaSelectList)
                setResult(Activity.RESULT_OK, intent)
                finish()
            }
            tipMsgDialog.show()
        } else {
            val intent = Intent()
            intent.putExtra(BaseHostActivity.DATA, agendaSelectList)
            setResult(Activity.RESULT_OK, intent)
            finish()
        }
    }

    override fun onBackPressed() {
        exit()
    }
}
